package abel.wlmr.model.type;

import abel.wlmr.model.WlmrException;
import abel.wlmr.model.WlmrField;

public class PeriodReportField extends WlmrField {

    private PeriodUnitType unit = PeriodUnitType.Hour;

    private byte period = 1;

    public PeriodReportField() {
        super(1);
    }

    @Override
    public int getValue() {
        if (unit == null) {
            throw new IllegalArgumentException("unit can't be null");
        }

        return (unit.getValue() << 6) | period;
    }

    @Override
    public void parseValue(int v) throws WlmrException {
        unit = PeriodUnitType.findUnitByValue((byte) ((v & 0xC0) >> 6));

        period = (byte) (v & 0x3F);
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return String.format("{%s %s}", unit, period);
    }

    /**
     * @return the unit
     */
    public PeriodUnitType getUnit() {
        return unit;
    }

    /**
     * @param unit
     *            the unit to set
     */
    public void setUnit(PeriodUnitType unit) {
        if (unit == null) {
            throw new IllegalArgumentException("unit can't be null");
        }

        this.unit = unit;
    }

    /**
     * @return the period
     */
    public byte getPeriod() {
        return period;
    }

    /**
     * @param period
     *            the period to set
     */
    public void setPeriod(byte period) {
        if (period < 1 || period > 63) {
            throw new IllegalArgumentException("period should be [1,63]");
        }
        this.period = period;
    }
}
